import 'dart:convert';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_search_bar_widget/common_search_bar_widget.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/media_detail_update.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/media_library_index_refresh_even.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/media_move_page_event.dart';
import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/bean/user_response_bean.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/company_address_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/bean/binding_terminal_edit_upload_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/bind_terminal_info_confirm_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/event/terminal_info_update_event.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/event/terminal_number_update_event.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/bean/scan_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/bean/terminal_by_pic_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/utils/utils.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/widgets/terminal_bind_success_dialog.dart';
import 'package:e_reception_flutter/ui/new_terminal/terminal_detail/widgets/operation_success_tips_dialog.dart';
import 'package:e_reception_flutter/ui/smart_home/event/refresh_smart_home_index_event.dart';
import 'package:e_reception_flutter/utils/app_monitoring_class.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_role_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:vg_base/src/arch/base_state.dart';
import 'package:vg_base/src/http/vg_http_response.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import '../../app_main.dart';
import 'bean/common_terminal_settings_response_bean.dart';
import 'bean/new_terminal_response_bean.dart';
import 'event/terminal_list_refresh_event.dart';

class NewTerminalListViewModel extends BasePagerViewModel<NewTerminalListItemBean,NewTerminalResponseBean>{

  static const String ADD_MEDIA_TO_TERMINALS_API =ServerApi.BASE_URL + "app/appAddPicByhsn";
  static const String ADD_MEDIA_LIST_TO_TERMINAL_API =ServerApi.BASE_URL + "app/appAddPicListByhsn";
  static const String GET_TERMINAL_LIST_BY_PIC_API =ServerApi.BASE_URL + "app/appGethsnBypicid";

  static const String TERMINAL_OFF_SCREEN_API =ServerApi.BASE_URL + "app/appCloseScreen";
  static const String TERMINAL_OFF_API =ServerApi.BASE_URL + "app/appClosePower";

  static const String SCAN_LOGIN_TERMINAL_API =ServerApi.BASE_URL + "app/appScanLoginTer";

  static const String SCAN_THEN_OPERATIONS_API =ServerApi.BASE_URL + "app/appScanOperation";

  static const String ADD_ORG_CHANNEL_API =ServerApi.BASE_URL + "app/appAddComBranch";

  // static const String TERMINAL_COMMON_SETTINGS_API =ServerApi.BASE_URL + "app/appGeneralSettings";
  static const String TERMINAL_COMMON_SETTINGS_API =ServerApi.BASE_URL + "app/findAutoSwitch";

  static const String SAVE_COMMON_SETTINGS_API =ServerApi.BASE_URL + "app/appSaveGeneralSettings";

  static const String SAVE_COMMON_SETTINGS_AUTO_ON_OFF_API =ServerApi.BASE_URL + "app/allAutoSwitchSetting";

  ///app放弃调整终端
  static const String EXIT_BIND_TERMINAL =
      ServerApi.BASE_URL + "app/appExitBinding";

  ValueNotifier<int> totalValueNotifier;
  final CommonSearchGetContentCallback searchStrFunc;
  final String allflg;
  final String gps;
  ValueNotifier<TerminalByPicDataBean> terminalByPicValueNotifier;
  ValueNotifier<List<NewTerminalListItemBean>> terminalByPicWithoutHsnValueNotifier;
  ValueNotifier<List<NewTerminalListItemBean>> terminalSearchValueNotifier;
  ValueNotifier<PlaceHolderStatusType> statusTypeValueNotifier;
  ///00扫描中 01扫描成功 02扫描失败
  ValueNotifier<String> scanValueNotifier;
  ValueNotifier<CommonTerminalSettingsBean> commonSettingsValueNotifier;
  ValueNotifier<CompanyAddressListInfoBean> addressValueNotifier;

  NewTerminalListViewModel(BaseState<StatefulWidget> state,   {this.searchStrFunc, this.allflg, this.gps}) : super(state){
    totalValueNotifier = ValueNotifier(0);
    terminalByPicValueNotifier = ValueNotifier(null);
    terminalByPicWithoutHsnValueNotifier = ValueNotifier(null);
    terminalSearchValueNotifier = ValueNotifier(null);
    statusTypeValueNotifier = ValueNotifier(PlaceHolderStatusType.loading);
    scanValueNotifier = ValueNotifier("01");
    commonSettingsValueNotifier = ValueNotifier(null);
    addressValueNotifier = ValueNotifier(null);
  }

  void getAddressList(BuildContext context){
    VgHttpUtils.post(NetApi.ADDRESS_LIST, params: {
      "authId": UserRepository.getInstance().authId ?? "",
      "current": 1,
      "gps":gps??"",
      "size": 20,
    }, callback: BaseCallback(
        onSuccess: (val){
          CompanyAddressBean bean = CompanyAddressBean.fromMap(val);
          if(!isStateDisposed){
            if(bean?.getDataList()?.isNotEmpty??false){
              addressValueNotifier?.value = bean?.getDataList()[0];
            }
          }
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(context, msg);
        }
    ));
  }

  void searchTerminal(BuildContext context, String searchContent){
    if(StringUtils.isEmpty(searchContent)){
      terminalSearchValueNotifier?.value?.clear();
      statusTypeValueNotifier?.value = PlaceHolderStatusType.empty;
      return;
    }
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.get(getUrl(), params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "companyid": UserRepository.getInstance().companyId ?? "",
      "current": 1,
      "size": 50,
      "flg": "01", //00全部 01绑定的
      "tname": searchContent??"",
      "gps":gps??"",
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context,);
          loading(false);
          NewTerminalResponseBean vo = NewTerminalResponseBean.fromMap(val);
          if(vo.getDataList().length > 0){
            terminalSearchValueNotifier?.value = vo.getDataList();
            statusTypeValueNotifier?.value = null;
          }else{
            statusTypeValueNotifier?.value = PlaceHolderStatusType.empty;
          }
        },
        onError: (msg){
          VgHudUtils.hide(context,);
          loading(false);
          statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
          VgToastUtils.toast(context, msg);
        }
    ));
  }

  ///添加已有资源到其他终端
  /// allflg 00 部分终端 01 全部终端
  void addMediaToTerminals(BuildContext context, String allflg, String startday,
      String endday, String hsns, String picid, {bool setTimeFlag, bool needPopToWait}){
    if(StringUtils.isEmpty(picid)){
      return;
    }
    if(VgRoleUtils.isCommonAdmin(UserRepository.getInstance().getCurrentRoleId())){
      //普通管理员上传文件时，就算选择了全部终端，是否选择全部终端的标识也应该是“否”
      allflg = "00";
    }
    loading(true, msg:"操作中");
    VgHttpUtils.get(ADD_MEDIA_TO_TERMINALS_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "picid": picid ?? "",
      "allflg": allflg ?? "",
      "startday": (StringUtils.isEmpty(hsns))?null:(startday ?? ""),
      "endday": (StringUtils.isEmpty(hsns))?null:(endday ?? ""),
      "hsns": hsns ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          loading(false);
          VgToastUtils.toast(context, "操作成功");
          if(setTimeFlag??false){
            RouterUtils.popUntil(context, AppMain.ROUTER,);
            VgEventBus.global.send(new MediaLibraryRefreshEven());
          }else{
            RouterUtils.pop(context, result: "操作成功");
            VgEventBus.global.send(new MediaLibraryRefreshEven());
          }

          VgEventBus.global.send(new MediaDetailUpdateEvent());
          if(needPopToWait??false){
            VgEventBus.global.send(new MediaMovePageEvent(2));
          }
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(context, msg);
        }
    ));
  }

  ///添加已有资源到其他终端
  /// allflg 00 部分终端 01 全部终端
  void addMediaListToTerminal(BuildContext context, String startday,
      String endday, String hsns, String picid, {bool needPopToWait}){
    if(StringUtils.isEmpty(picid)){
      return;
    }
    loading(true, msg:"添加中");
    VgHttpUtils.get(ADD_MEDIA_LIST_TO_TERMINAL_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "picids": picid ?? "",
      "startday": (StringUtils.isEmpty(hsns))?null:(startday ?? ""),
      "endday": (StringUtils.isEmpty(hsns))?null:(endday ?? ""),
      "hsn": hsns ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          loading(false);
          VgToastUtils.toast(context, "添加成功");
          RouterUtils.pop(context, result: "添加成功");
          VgEventBus.global.send(new MediaDetailUpdateEvent());
          if(needPopToWait??false){
            VgEventBus.global.send(new MediaMovePageEvent(2));
          }
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(context, msg);
        }
    ));
  }


  ///根据图片获取可选终端列表
  void getTerminalListByPic(BuildContext context, String picid, String hsn, {String terminalname}){
    VgHttpUtils.get(GET_TERMINAL_LIST_BY_PIC_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "picid": picid ?? "",
      "hsn": hsn ?? "",
      "flg": allflg??"00", //00全部 01绑定的
      // if(StringUtils.isNotEmpty(searchStrFunc?.call() ?? ""))
      "terminalname":terminalname?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          TerminalByPicResponseBean bean = TerminalByPicResponseBean.fromMap(val);
          if(!isStateDisposed){
            if(bean?.data?.terminalList != null && bean.data.terminalList.length > 0){
              statusTypeValueNotifier?.value = null;
              terminalByPicValueNotifier?.value = bean?.data;
            }else{
              statusTypeValueNotifier?.value = PlaceHolderStatusType.empty;
            }
          }
          loading(false);
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(context, msg);
          statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
        }
    ));
  }


  ///根据图片获取可选终端列表
  void getTerminalListByPicWithoutHsn(BuildContext context, String picid,{String terminalname}){
    VgHttpUtils.get(GET_TERMINAL_LIST_BY_PIC_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "picid": picid ?? "",
      // if(StringUtils.isNotEmpty(searchStrFunc?.call() ?? ""))
      "terminalname":terminalname?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          TerminalByPicResponseBean bean = TerminalByPicResponseBean.fromMap(val);
          if(!isStateDisposed){
            if(bean?.data?.terminalList != null && bean.data.terminalList.length > 0){
              statusTypeValueNotifier?.value = null;
              List<NewTerminalListItemBean> data = new List();
              TerminalByPicDataBean detailBean = bean.data;

              List<String> pichsnList = new List();
              if(detailBean?.usehsnList != null && (detailBean?.usehsnList?.length??0) > 0){
                detailBean.usehsnList.forEach((element) {
                  pichsnList.add(element.hsn);
                });
              }
              //有已经选中的终端先加已经选中的
              if(pichsnList.length > 0){
                detailBean.terminalList.forEach((element) {
                  if(pichsnList.contains(element.hsn)){
                    element.selectStatus = true;
                  }else{
                    element.selectStatus = false;
                  }
                  data.add(element);
                });
              }else{
                //没有已经选中的
                data.addAll(detailBean?.terminalList);
              }
              terminalByPicWithoutHsnValueNotifier?.value = data;
            }else{
              statusTypeValueNotifier?.value = PlaceHolderStatusType.empty;
            }
          }
          loading(false);
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(context, msg);
          statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
        }
    ));
  }

  ///终端关闭电源
  void terminalOffScreen(BuildContext context, String hsn, String screenStatus, {VoidCallback callback}){
    if(StringUtils.isEmpty(hsn)){
      VgToastUtils.toast(context, "设备信息异常");
      return;
    }
    if("01" == screenStatus){
      screenStatus = "02";
    }
    loading(true, msg:"通讯中...");
    VgHttpUtils.get(TERMINAL_OFF_SCREEN_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "hsn": hsn ?? "",
      "screenStatus": screenStatus ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          loading(false);
          VgEventBus.global.send(new TerminalListRefreshEvent());
          OperationSuccessTipsDialog.navigatorPushDialog(context);
          if(callback != null){
            callback.call();
          }
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(context, msg);
        }
    ));
  }

  ///关闭终端
  void terminalOff(BuildContext context, String hsn, {VoidCallback callback}){
    if(StringUtils.isEmpty(hsn)){
      VgToastUtils.toast(context, "设备信息异常");
      return;
    }
    //先全做息屏操作

    terminalOffScreen(context, hsn, "01", callback: callback);
    // if("15F2A8A5A1F9547969F924BC7FC5151133" == hsn){
    //   CommonISeeDialog.navigatorPushDialog(context, title: "提示",
    //       content:"当前设备不支持远程关机");
    //   return;
    // }
    // loading(true, msg:"通讯中...");
    // VgHttpUtils.get(TERMINAL_OFF_API,params: {
    //   "authId":UserRepository.getInstance().authId ?? "",
    //   "hsn": hsn ?? "",
    // },callback: BaseCallback(
    //     onSuccess: (val){
    //       loading(false);
    //       VgEventBus.global.send(new TerminalListRefreshEvent());
    //       OperationSuccessTipsDialog.navigatorPushDialog(context);
    //       if(callback != null){
    //         callback.call();
    //       }
    //     },
    //     onError: (msg){
    //       loading(false);
    //       VgToastUtils.toast(context, msg);
    //     }
    // ));
  }

  ///扫码登录
  void scanLogin(BuildContext context, String hsn){
    if(StringUtils.isEmpty(hsn)){
      VgToastUtils.toast(context, "设备信息异常");
      return;
    }
    scanValueNotifier.value = "00";
    loading(true, msg:"处理中");
    VgHttpUtils.get(SCAN_LOGIN_TERMINAL_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "hsn": hsn ?? "",
      "gps": gps ?? "",
    },callback: BaseCallback(
        onSuccess: (val)async{
          loading(false);
          ScanResponseBean bean = ScanResponseBean.fromMap(val);
          if(bean != null && bean.data != null){
            if("00" == bean.data.have){
              scanThenOperations(hsn, "13");
              RouterUtils.pop(context, result: true);
            }else if("01" == bean.data.have){
              //扫码登录并绑定
              RouterUtils.pop(context);
              UserDataBean userDataBean = UserRepository.getInstance().userData;
              String orgName = "";
              if(!StringUtils.isEmpty(userDataBean?.companyInfo?.companynick??"")){
                orgName = userDataBean?.companyInfo?.companynick??"";
              }else{
                orgName = userDataBean?.companyInfo?.companyname??"";
              }
              if(userDataBean != null && userDataBean.companyList != null && userDataBean.companyList.length > 1){
                bool addResult = await CommonConfirmCancelDialog.navigatorPushDialog(AppMain.context,
                  title: "提示",
                  content: "确定将当前显示屏添加至${orgName}机构？",
                  cancelText: "取消",
                  confirmText: "确定",
                  confirmBgColor:
                  ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                );
                if (addResult??false) {
                  bool result = await TerminalBindSuccessDialog.navigatorPushDialog(AppMain.context,
                      bean.data.rcaid, hsn, (bean?.data?.terName??"终端显示屏1"),
                      (bean?.data?.position??"请选择"), RouteSettings(name: 'TerminalBindSuccessDialog'));
                  if(result == null){
                    BindingTermialEditUploadBean _uploadBean = BindingTermialEditUploadBean();
                    _uploadBean
                      ..flg = "00"
                      ..terminal_name = (bean?.data?.terName??"终端显示屏1")
                      ..rcaid = bean.data.rcaid
                      ..hsn = hsn
                      ..position = (bean?.data?.position??"请选择")
                      ..caid = bean?.data?.caid??""
                    ;
                    toSaveTerminalInfo(context, _uploadBean);
                    scanThenOperations(hsn, "16");
                  }else{
                    scanThenOperations(hsn, "16");
                  }
                }else{
                  RouterUtils.pop(context, result: false);
                }
              }else{
                bool result = await TerminalBindSuccessDialog.navigatorPushDialog(AppMain.context,
                    bean.data.rcaid, hsn, (bean?.data?.terName??"终端显示屏1"),
                    (bean?.data?.position??"请选择"), RouteSettings(name: 'TerminalBindSuccessDialog'));
                if(result == null){
                  BindingTermialEditUploadBean _uploadBean = BindingTermialEditUploadBean();
                  _uploadBean
                    ..flg = "00"
                    ..terminal_name = (bean?.data?.terName??"终端显示屏1")
                    ..rcaid = bean.data.rcaid
                    ..hsn = hsn
                    ..position = (bean?.data?.position??"请选择")
                    ..caid = bean?.data?.caid??"";
                  toSaveTerminalInfo(context, _uploadBean);
                  scanThenOperations(hsn, "16");
                }else{
                  scanThenOperations(hsn, "16");
                }
              }
            }else if("02" == bean.data.have){
              UserDataBean userDataBean = UserRepository.getInstance().userData;
              String orgName = "";
              if(!StringUtils.isEmpty(userDataBean?.companyInfo?.companynick??"")){
                orgName = userDataBean?.companyInfo?.companynick??"";
              }else{
                orgName = userDataBean?.companyInfo?.companyname??"";
              }
              if(userDataBean != null && userDataBean.companyList != null && userDataBean.companyList.length > 1){
                bool addResult = await CommonConfirmCancelDialog.navigatorPushDialog(AppMain.context,
                    title: "提示",
                    content: "确定将当前显示屏添加至${orgName}机构？",
                    cancelText: "取消",
                    confirmText: "确定",
                    confirmBgColor:
                    ThemeRepository.getInstance().getPrimaryColor_1890FF());
                if (addResult ?? false) {
                  //跳转到绑定确认的页面
                  scanThenOperations(hsn, "14");
                  dynamic result = await RouterUtils.pushAndPop(context,
                      BindTerminalInfoConfirmPage(hsn: hsn,
                        defaultName: (bean?.data?.terName??"终端显示屏1"),
                        defaultPosition: (bean?.data?.position??"请选择"),), result: true);
                  if(result == null){
                    exitBindTerminal(hsn);
                  }
                }else{
                  RouterUtils.pop(context, result: false);
                }
              }else{
                //跳转到绑定确认的页面
                scanThenOperations(hsn, "14");
                dynamic result = await RouterUtils.pushAndPop(context,
                    BindTerminalInfoConfirmPage(hsn: hsn,
                      defaultName: (bean?.data?.terName??"终端显示屏1"),
                      defaultPosition: (bean?.data?.position??"请选择"),), result: true);
                if(result == null){
                  exitBindTerminal(hsn);
                }
              }
            }
            if(!isStateDisposed){
              Future.delayed(Duration(milliseconds: 1000),(){
                scanValueNotifier.value = "01";
              });
            }

          }else{
            VgToastUtils.toast(context, bean?.msg??"");
            if(!isStateDisposed){
              Future.delayed(Duration(milliseconds: 1000),(){
                scanValueNotifier.value = "02";
              });
            }
          }
        },
        onError: (msg){
          if(!isStateDisposed){
            Future.delayed(Duration(milliseconds: 1000),(){
              scanValueNotifier.value = "02";
            });
          }
          loading(false);
          if((msg??"").contains("未查询到终端信息")){
            VgToastUtils.toast(context, "未查询到终端信息，请稍后再试或退出重进");
          }else{
            VgToastUtils.toast(context, msg);
          }
        }
    ));
  }

  ///扫码登录
  void scanLoginNew(BuildContext context, String hsn, Function(ScanResultBean) callback){
    if(StringUtils.isEmpty(hsn)){
      VgToastUtils.toast(context, "设备信息异常");
      return;
    }
    scanValueNotifier.value = "00";
    loading(true, msg:"处理中");
    VgHttpUtils.get(SCAN_LOGIN_TERMINAL_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "hsn": hsn ?? "",
      "gps": gps ?? "",
    },callback: BaseCallback(
        onSuccess: (val)async{
          loading(false);
          ScanResponseBean bean = ScanResponseBean.fromMap(val);
          if(bean != null && bean.data != null){
            callback.call(bean.data);
            if(!isStateDisposed){
              Future.delayed(Duration(milliseconds: 1000),(){
                scanValueNotifier.value = "01";
              });
            }

          }else{
            VgToastUtils.toast(context, bean?.msg??"");
            if(!isStateDisposed){
              Future.delayed(Duration(milliseconds: 1000),(){
                scanValueNotifier.value = "02";
              });
            }
          }
        },
        onError: (msg){
          if(!isStateDisposed){
            Future.delayed(Duration(milliseconds: 1000),(){
              scanValueNotifier.value = "02";
            });
          }
          loading(false);
          if((msg??"").contains("未查询到终端信息")){
            VgToastUtils.toast(context, "未查询到终端信息，请稍后再试或退出重进");
          }else{
            VgToastUtils.toast(context, msg);
          }
        }
    ));
  }

  ///app终端管理保存绑定信息
  static const String TERMINAL_SAVE_INFO_API =
      ServerApi.BASE_URL + "app/appSaveTerminalInfo";

  void toSaveTerminalInfo(
      BuildContext context, BindingTermialEditUploadBean uploadBean, {VoidCallback callback, bool showHud}) {
    VgHudUtils.show(context, "保存中");
    VgHttpUtils.get(TERMINAL_SAVE_INFO_API,
        params:
        {
          "mid": uploadBean?.mid ?? "",
          "flg": uploadBean?.flg??"",
          "authId": UserRepository.getInstance().authId ?? "",
          "rcaid": uploadBean?.rcaid ?? 0,
          "cbid": uploadBean?.cbid ?? "",
          "hsn": uploadBean?.hsn ?? "",
          "position": uploadBean?.position ?? "",
          "cameratype": uploadBean?.cameratype ?? "00",
          "correct_camera": uploadBean?.correctCamera ?? 0,
          "auto_onoff_time": uploadBean?.getAutoOffTimeStr() ?? "",
          "start_camera_distance": uploadBean?.cameraStartDistance ?? "",
          "terminal_name": uploadBean?.terminal_name ?? "",
          "terminal_picurl": uploadBean?.terminal_picurl ?? "",
          "time_interval": uploadBean?.punchInInterval ?? "",
          "scanFlg":"01",
          if(StringUtils.isNotEmpty(uploadBean?.caid??""))"caid":uploadBean?.caid,
        },
        callback: BaseCallback(onSuccess: (val) {
          VgHudUtils.hide(context);
          if(showHud??true){
            VgToastUtils.toast(AppMain.context, "保存成功");
          }
          if(callback != null){
            callback();
          }else{
            RouterUtils.pop(context);
          }
        }, onError: (msg) {
          VgHudUtils.hide(context);
          if("请检测对应终端是否在线。" == msg){
            if(callback != null){
              callback();
            }else{
              RouterUtils.pop(context);
            }
            VgToastUtils.toast(AppMain.context, "保存成功");
          }else{
            VgToastUtils.toast(AppMain.context, msg);
          }
        }));
  }

  ///智能家居绑定终端
  void smartHomeBindTerminal(BuildContext context, int rcaid, String hsn, String shid,
      String backup, String position, String picurl, VoidCallback callback){
    VgHudUtils.show(context, "保存中");
    VgHttpUtils.get(NetApi.SMART_HOME_BIND_TERMINAL,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "rcaid": rcaid??"",
          "hsn": hsn??"",
          "shid": shid?? "",
          "backup": backup?? "",
          "terminal_name": backup?? "",
          "position": position?? "",
          "terminal_picurl": picurl?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, "保存成功");
          callback();
        }, onError: (msg) {
          VgHudUtils.hide(context);
          if("请检测对应终端是否在线。" == msg){
            callback();
            VgToastUtils.toast(AppMain.context, "保存成功");
          }else{
            VgToastUtils.toast(AppMain.context, msg);
          }
        }));
  }

  ///app正在绑定终端
  void exitBindTerminal(String hsnId) {
    if (StringUtils.isEmpty(hsnId)) {
      return;
    }
    VgHttpUtils.get(EXIT_BIND_TERMINAL,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "hsn": hsnId ?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          BaseResponseBean bean =
          BaseResponseBean.fromMap(val);
        }, onError: (msg) {
          VgToastUtils.toast(AppMain.context, msg);
          statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
        }));
  }

  ///扫码后续得操作，通知终端
  ///key 13扫码登录 14扫码绑定 16扫码登录并绑定
  void scanThenOperations(String hsn, String key) {
    if (StringUtils.isEmpty(hsn)) {
      return;
    }
    VgHttpUtils.get(SCAN_THEN_OPERATIONS_API,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "hsn": hsn ?? "",
          "key": key ?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          BaseResponseBean bean =
          BaseResponseBean.fromMap(val);
          if("13" == key){
            VgHudUtils.show(AppMain.context, "登录中...");
          }else{
            VgHudUtils.show(AppMain.context, "配置中...");
          }
          Future.delayed(Duration(milliseconds: 5000), (){
            VgEventBus.global.send(new TerminalListRefreshEvent());
            VgEventBus.global.send(new TerminalNumberUpdateEvent("扫码操作"));
            VgEventBus.global.send(new RefreshSmartHomeIndexEvent());
            VgHudUtils.hide(AppMain.context);
          });
        }, onError: (msg) {
          VgToastUtils.toast(AppMain.context, msg);
        }));
  }

  ///添加机构分支
  void addOrgChannel(BuildContext context, String addrCity, String addrCode,
      String addrDistrict, String addrProvince, String address, String branchname,
      String gps, String cbid, String gpsadress, VoidCallback callback){
    VgHudUtils.show(context, "添加中");
    VgHttpUtils.post(ADD_ORG_CHANNEL_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "addrCity": addrCity ?? "",
      "addrCode": addrCode ?? "",
      "addrDistrict": addrDistrict??"",
      "addrProvince":addrProvince?? "",
      "address":address?? "",
      "branchname":branchname?? "",
      "gps":gps?? "",
      "cbid":cbid?? "",
      "gpsadress":gpsadress?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          callback.call();
        },
        onError: (msg){
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }
    ));
  }

  ///获取终端通用设置
  void getTerminalCommonSettings(BuildContext context){
    VgHttpUtils.post(TERMINAL_COMMON_SETTINGS_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          CommonTerminalSettingsResponseBean bean = CommonTerminalSettingsResponseBean.fromMap(val);
          if(!isStateDisposed){
            statusTypeValueNotifier?.value = null;
            commonSettingsValueNotifier?.value = bean?.data;
          }
          loading(false);
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(context, msg);
          statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
        }
    ));
  }

  ///保存通用设置
  void saveCommonSettings(BuildContext context, String autoOnOffTime,
      String autoOnoff, String enableFaceRecognition,
      int volume, VoidCallback callback){
    //autoOnoff 00未设置 01已设置
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.get(SAVE_COMMON_SETTINGS_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "autoOnoffTime": autoOnOffTime ?? "",
      "autoOnoff": autoOnoff ?? "01",
      "enableFaceRecognition": enableFaceRecognition ?? "",
      "volume": volume??"",
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, "操作成功");
          VgEventBus.global.send(new TerminalInfoUpdateEvent("通用设置更新"));
          callback.call();
        },
        onError: (msg){
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }
    ));
  }

  ///保存通用设置
  void saveCommonSettingsByAutoOnOff(BuildContext context, String autoOnOffTime,
      String autoOnoff,  String week, VoidCallback callback){
    //autoOnoff 00未设置 01已设置
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.get(SAVE_COMMON_SETTINGS_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "autoOnoffTime": autoOnOffTime ?? "",
      "autoOnoff": autoOnoff ?? "01",
      "autoOnoffWeek": week ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, "操作成功");
          VgEventBus.global.send(new TerminalInfoUpdateEvent("通用设置更新"));
          callback.call();
        },
        onError: (msg){
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }
    ));
  }

  ///保存通用设置
  void saveCommonSettingsByFaceRecognition(BuildContext context, String enableFaceRecognition, VoidCallback callback){
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.get(SAVE_COMMON_SETTINGS_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "enableFaceRecognition": enableFaceRecognition ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, "操作成功");
          VgEventBus.global.send(new TerminalInfoUpdateEvent("通用设置更新"));
          callback.call();
        },
        onError: (msg){
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }
    ));
  }

  ///保存通用设置
  void saveCommonSettingsByVolume(BuildContext context, int volume, VoidCallback callback){
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.get(SAVE_COMMON_SETTINGS_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "volume": volume ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, "操作成功");
          VgEventBus.global.send(new TerminalInfoUpdateEvent("通用设置更新"));
          callback.call();
        },
        onError: (msg){
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }
    ));
  }

  ///保存通用设置自动开关机
  void saveAutoOnOffByWeek(BuildContext context, ComAutoSwitchBean comAutoSwitch, VoidCallback callback, {bool noToast}){
    //autoOnoff 00未设置 01已设置
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.post(SAVE_COMMON_SETTINGS_AUTO_ON_OFF_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "companyid": UserRepository.getInstance().companyId ?? "",

      "autoOnoff": comAutoSwitch?.autoOnoff ?? "00",

      "autoMon": comAutoSwitch?.autoMon ?? "00",
      "autoTues": comAutoSwitch?.autoTues ?? "00",
      "autoWed": comAutoSwitch?.autoWed ?? "00",
      "autoThur": comAutoSwitch?.autoThur ?? "00",
      "autoFri": comAutoSwitch?.autoFri ?? "00",
      "autoSat": comAutoSwitch?.autoSat ?? "00",
      "autoSun": comAutoSwitch?.autoSun ?? "00",

      "monTime": comAutoSwitch?.monTime ?? "",
      "tuesTime": comAutoSwitch?.tuesTime ?? "",
      "wedTime": comAutoSwitch?.wedTime ?? "",
      "thurTime": comAutoSwitch?.thurTime ?? "",
      "friTime": comAutoSwitch?.friTime ?? "",
      "satTime": comAutoSwitch?.satTime ?? "",
      "sunTime": comAutoSwitch?.sunTime ?? "",
      "restflg": comAutoSwitch?.restflg ?? "01",


    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          if(!(noToast??false)){
            VgToastUtils.toast(AppMain.context, "操作成功");
          }
          VgEventBus.global.send(new TerminalInfoUpdateEvent("通用设置更新"));
          callback.call();
        },
        onError: (msg){
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }
    ));
  }

  @override
  void onDisposed() {
    if(!isStateDisposed){
      totalValueNotifier?.dispose();
      statusTypeValueNotifier?.dispose();
      terminalByPicValueNotifier?.dispose();
      terminalSearchValueNotifier?.dispose();
      terminalByPicWithoutHsnValueNotifier?.dispose();
      addressValueNotifier?.dispose();
    }
    // scanValueNotifier?.dispose();
    super.onDisposed();
  }

  @override
  String getBodyData(int page) {
    return null;
  }

  @override
  Map<String, dynamic> getQuery(int page) {
    // Future<String> latlng = VgLocationUtils.getCacheLatLngString();
    // latlng.then((value) {
    //   Map<String, dynamic> map = {
    //     "authId": UserRepository.getInstance().authId ?? "",
    //     "companyid": UserRepository.getInstance().companyId ?? "",
    //     "current": page ?? 1,
    //     "size": 20,
    //     "flg": allflg??"00", //00全部 01绑定的
    //     if(StringUtils.isNotEmpty(searchStrFunc?.call() ?? ""))
    //       "tname":searchStrFunc?.call() ?? "",
    //     "gps": value??null,
    //   };
    //   return map;
    // });
    Map<String, dynamic> map = {
      "authId": UserRepository.getInstance().authId ?? "",
      "companyid": UserRepository.getInstance().companyId ?? "",
      "current": page ?? 1,
      "size": 20,
      "flg": allflg??"00", //00全部 01绑定的
      if(StringUtils.isNotEmpty(searchStrFunc?.call() ?? ""))
        "tname":searchStrFunc?.call() ?? "",
      "gps":gps??"",
    };
    return map;

  }

  @override
  String getRequestMethod() {
    return HttpUtils.GET;
  }

  @override
  String getUrl() {
    return ServerApi.BASE_URL + "app/appTerminalList";
  }

  @override
  NewTerminalResponseBean parseData(VgHttpResponse resp) {
    NewTerminalResponseBean vo = NewTerminalResponseBean.fromMap(resp?.data);
    loading(false);
    totalValueNotifier?.value = vo?.data?.page?.total ?? 0;
    SharePreferenceUtil.putString(NewTerminalListUtils.getTerminalListCacheKey(), json.encode(vo?.data?.page?.records));
    return vo;
  }

}